﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;

namespace Landscape.WebApp.SignalR
{
    [HubName("ScribeMini")]
    public class ScribeSignalHub : Hub
    {
        private static readonly ConcurrentDictionary<string, Guid> clientIncidentList = new ConcurrentDictionary<string, Guid>();
        private readonly Scribe _scribe;

        public ScribeSignalHub() : this(Scribe.Instance) { }

        public ScribeSignalHub(Scribe scribe)
        {
            // TODO: Complete member initialization
            this._scribe = scribe;
        }

        public Task AddToIncident(Guid pIncID)
        {
            while (!clientIncidentList.TryAdd(Context.ConnectionId, pIncID))
            { //Wait till the cliet get disconnected 
                Thread.Sleep(1000);
            }

            return Groups.Add(Context.ConnectionId, pIncID.ToString());
        }

        public IList<ScribeItem> GetScribeLogAfter(int pLastItemID)
        {   
            Guid incID = Guid.Empty;
            clientIncidentList.TryGetValue(Context.ConnectionId, out incID);

            return this._scribe.GetScribeLogAfter(pLastItemID, incID);
        }

        public void AddToScribeLog(ScribeItem pItem)
        {
            this._scribe.AddToScribeLog(pItem);
        }

        public override Task OnDisconnected()
        {
            Guid incID = Guid.Empty;
            clientIncidentList.TryRemove(Context.ConnectionId, out incID);

            if (clientIncidentList.Where(exp => exp.Value == incID).Count() == 0)
            {
                this._scribe.ClearEntriesFor(incID);
            }

            return this.Groups.Remove(Context.ConnectionId, incID.ToString());
        }
    }
}